package com.dashan.backend.datastore;

import javax.jdo.PersistenceManager;
import javax.jdo.Query;

import com.dashan.backend.PMF;

public abstract class DaoBase {
    protected PersistenceManager pm;
        
    public DaoBase() {
        pm = PMF.get().getPersistenceManager();
    }
    
    /**
     * Delete all records of this type in the data store!
     */
    @SuppressWarnings("unchecked")
    public void deleteAll(Class clazz) {
        Query query = pm.newQuery(clazz);
        query.deletePersistentAll();
    }

    public void startTransaction() {
        pm.currentTransaction().begin();
    }
    
    public void endTransaction() {
        pm.currentTransaction().commit();
    }
    
    public void checkTransacton() {
        if (pm.currentTransaction().isActive()) {
            pm.currentTransaction().rollback();
        }
    }
    
    public void commit() {
        pm.close();
    }
    
    @Override
    protected void finalize() throws Throwable {
        if (!pm.isClosed()) {
            pm.close();
        }
        super.finalize();
    }
}
